package com.tl.common.video;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Display;
import android.widget.Toast;

import com.tl.common.util.FileSizeUtil;
import com.tl.tlcommon.R;

@SuppressLint("DefaultLocale")
public class VideoHelper {

	public final static int TAKE_VIDEO = 4000; // 录像
	public final static int SELECT_VIDEO = 4001; // 图库选择录像

	private int source;

	VideoResultCallback mListener;
	private Activity context = null;
	// private Uri mSaveUri;

	private String mSaveVideoName;
	private String mSaveVideoType = ".3gp";

	private String FILE_SAVEPATH = "";

	boolean isSDCard = true;
	int mScreenWidth = 480;
	int mScreenHeight = 800;

	double mMaxFileSize = 50; // 最大文件大小,以兆为单位

	public static interface VideoResultCallback {
		/**
		 * 返回结果
		 * 
		 * @param result
		 *            视频的存放地址
		 */
		void onResult(String result);
	}

	public VideoHelper(Activity context) {
		super();
		this.context = context;

		// 首先取得屏幕对象
		Display display = context.getWindowManager().getDefaultDisplay();
		// 获取屏幕的宽和高
		mScreenWidth = display.getWidth();
		mScreenHeight = display.getHeight();

	}

	public void setMaxFileSiez(double size) {
		mMaxFileSize = size;
	}

	public void setSavePath(String savePath) {
		FILE_SAVEPATH = savePath;

		// 判断是否挂载了SD卡
		try {
			String storageState = Environment.getExternalStorageState();
			if (storageState.equals(Environment.MEDIA_MOUNTED)) {
				File savedir = new File(FILE_SAVEPATH);
				if (!savedir.exists()) {
					savedir.mkdirs();
				}
			} else {
				isSDCard = false;
				// UIHelper.ToastMessage(UserInfo.this, "无法保存上传的头像，请检查SD卡是否挂载");
				return;
			}
		} catch (Exception e) {
			Toast.makeText(context, "无法创建图片保存目录,错误:" + e.getMessage(), -1)
					.show();
		}
	}

	public String getVideoFilePath() {
		String path = getSaveVideoPath();
		boolean exits = new File(path).exists();
		return exits ? path : "";
	}

	public String getVideoFileName() {
		String path = getSaveVideoPath();
		boolean exits = new File(path).exists();
		return exits ? mSaveVideoName + mSaveVideoType : "";
	}

	/**
	 * 开启相机或者图库,并且进行图片剪切
	 * 
	 * @param callback
	 *            回调函数
	 * @param source
	 *            调用参数:FROM_CAMERA相机 FROM_MEDIA图库
	 */
	public void fetchVideo(VideoResultCallback callback, int source) {
		if (!isSDCard) {
			Toast.makeText(context, "无法保存拍照的图片，请检查SD卡是否挂载", Toast.LENGTH_SHORT)
					.show();
			return;
		}

		this.mListener = callback;
		this.source = source;

		// 输出裁剪的临时文件
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		// 照片命名
		mSaveVideoName = "app_" + timeStamp;
		// cropFileName = "app_crop_" + timeStamp + ".jpg";

		// cropUri = Uri.fromFile(new File(FILE_SAVEPATH, cropFileName));

		switch (this.source) {
		case TAKE_VIDEO:
			startActionCamera(getSaveVideoUrl());
			break;
		case SELECT_VIDEO:
			startActionPick(getSaveVideoUrl());

			break;
		}
	}

	private Uri getSaveVideoUrl() {
		return Uri.fromFile(new File(FILE_SAVEPATH, mSaveVideoName
				+ mSaveVideoType));
	}

	private String getSaveVideoPath() {
		return FILE_SAVEPATH + mSaveVideoName + mSaveVideoType;
	}

	/**
	 * 相机拍照,保存为文件,如果使用data返回,图片质量太差
	 * 
	 * @param output
	 */
	private void startActionCamera(Uri output) {

		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		// intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
		context.startActivityForResult(intent, TAKE_VIDEO);

	}

	/**
	 * 选择视频
	 * 
	 * @param output
	 */
	private void startActionPick(Uri output) {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("video/*");
		// intent.putExtra("output", output);
		context.startActivityForResult(Intent.createChooser(intent, "选择视频"),
				SELECT_VIDEO);

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK
				&& (requestCode == TAKE_VIDEO || requestCode == SELECT_VIDEO)) {
			return;
		}

		if (data != null) {
			Uri uriVideo = data.getData();
			Cursor cursor = context.getContentResolver().query(uriVideo, null,
					null, null, null);

			if (cursor != null && cursor.moveToNext()) {
				/* _data：文件的绝对路径 ，_display_name：文件名 */
				String strVideoPath = cursor.getString(cursor
						.getColumnIndex("_data"));
				// Toast.makeText(context, strVideoPath, Toast.LENGTH_SHORT)
				// .show();

				// 在这里替换下文件名称，改成你想要的名称
				saveFile(strVideoPath);
				return;
			}

			if (uriVideo.getScheme().compareTo("file") == 0) {
				// file:///开头的uri

				String fileName = uriVideo.getPath().toString();
				// fileName = uriVideo.toString().replace("file://", "");
				// 替换file://
				// fileName = fileName.replace("/storage", "");

				// 去掉"/mnt"头
				// if (!fileName.startsWith("/mnt"))
				// fileName = fileName.replace("/mnt", "");

				saveFile(fileName);
				return;
			}

			if (uriVideo.getScheme().toString().compareTo("content") == 0) {
				// content://开头的uri
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor actualimagecursor = context.managedQuery(uriVideo, proj,
						null, null, null);
				if (actualimagecursor != null) {
					int actual_image_column_index = actualimagecursor
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					actualimagecursor.moveToFirst();
					String img_path = actualimagecursor
							.getString(actual_image_column_index);

					saveFile(img_path);
					return;
				}
			}
		}

	}

	private void saveFile(String videoPath) {
		File file = new File(videoPath);

		double fileSize = FileSizeUtil.getFileOrFilesSize(videoPath, 3);
		if (fileSize > mMaxFileSize) {
			Toast.makeText(context,
					"文件大小超过" + mMaxFileSize + "兆,大小为" + fileSize + "兆!", -1)
					.show();
			return;
		}

		if (videoPath.toLowerCase().endsWith(".mp4")) {
			mSaveVideoType = ".mp4";
		} else if (videoPath.toLowerCase().endsWith(".3gp")) {
			mSaveVideoType = ".3gp";
		} else if (videoPath.toLowerCase().endsWith(".mov")) {
			mSaveVideoType = ".mov";
		} else if (videoPath.toLowerCase().endsWith(".wmv")) {
			mSaveVideoType = ".wmv";
		}

		if (file.exists()) {
			String newPath = getSaveVideoPath();
			if (!newPath.equals(videoPath)) {
				// CopySdcardFile(videoPath, newPath);
				new MyTask().execute(videoPath, newPath);
			} else {
				// Toast.makeText(context, newPath, -1).show();
				if (mListener != null)
					mListener.onResult(newPath);
			}
		}
	}

	private class MyTask extends AsyncTask<String, String, Integer> {
		String ErrorMessage;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			if (progressDialog == null) {
				initProgressDialog();
			}
			progressDialog.show();

			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				String fromFile = params[0];
				String toFile = params[1];

				InputStream fosfrom = new FileInputStream(fromFile);
				OutputStream fosto = new FileOutputStream(toFile);
				byte bt[] = new byte[1024];
				int c;
				while ((c = fosfrom.read(bt)) > 0) {
					fosto.write(bt, 0, c);
				}
				fosfrom.close();
				fosto.close();
				return 0;

			} catch (Exception ex) {
				ErrorMessage = ex.getMessage();
				return -1;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			progressDialog.dismiss();
			if (result < 0) {
				Toast.makeText(context, "复制文件失败!" + ErrorMessage, -1).show();
			} else {
				String newPath = getSaveVideoPath();
				if (mListener != null)
					mListener.onResult(newPath);
			}

			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			progressDialog.dismiss();
			super.onCancelled();
		}

	}

	ProgressDialog progressDialog;

	private void initProgressDialog() {
		progressDialog = new ProgressDialog(context);
		progressDialog.setMessage("正在复制视频");
		progressDialog.show();

	}

}
